#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <chrono>

using namespace std;

queue<int> shared_queue;
mutex mtx;
condition_variable cv;

bool finished = false;  // 控制是否退出

// 生产者
void producer() {
    for (int i = 1; i <= 10; ++i) {
        {
            lock_guard<mutex> lock(mtx);
            shared_queue.push(i);
            cout << "[Producer] pushed: " << i << endl;
        }
        cv.notify_one();  // 通知消费者
        this_thread::sleep_for(chrono::milliseconds(300));
    }
    // 通知消费者准备退出
    {
        lock_guard<mutex> lock(mtx);
        finished = true;
    }
    cv.notify_all();
}

void consumer() {
    while(true) {
        unique_lock<mutex> lock(mtx);
        cv.wait(lock, []() { return !shared_queue.empty() || finished; });
        while(!shared_queue.empty()) {
            int val = shared_queue.front();
            shared_queue.pop();
            cout << " [Consumer] got: " << val << endl;
        }
        if(finished) break;
    }
}

int main() {
    thread t1(producer);
    thread t2(consumer);

    t1.join();
    t2.join();

    cout << "All tasks done." << endl;
    return 0;
}
